package com.scut.fy.common.web.util;

import cn.dev33.satoken.stp.StpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.server.ServerWebExchange;

import javax.servlet.http.HttpServletRequest;


/**
 * 根据请求头获取相应的用户信息
 *
 * @author JY
 * @version 1.0
 * @date 2021/9/28
 */
public class UserUtil {
    /**
     * token请求头别名
     */
    public static final String REQ_HEADER = "Endure";
    /**
     * token分割符，注意有个空格
     */
    public static final String TOKEN_SPLIT = "Bearer ";

    private static final Logger log = LoggerFactory.getLogger(UserUtil.class);

    /**
     * webMVC请求
     * @param servletRequest
     * @return
     */
    public static Long getUserId(final HttpServletRequest servletRequest) {
        Long userId = null;
        final String authorization = servletRequest.getHeader(REQ_HEADER);
        if (null == authorization || StringUtils.isEmpty(authorization) ) {
            log.error("用户异常");
        }
        // token分割
        final String token = StringUtils.substringAfter(authorization,
                TOKEN_SPLIT);
        // 根据token获取用户id
        userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
        return userId;
    }

    /**
     * webflux请求
     * @param exchange
     * @return
     */
    public static long getUserId(final ServerWebExchange exchange) {
        final String authorization = exchange.getRequest().getQueryParams().getFirst(REQ_HEADER);
        if (null == authorization || StringUtils.isEmpty(authorization) ) {
            log.error("用户异常");
        }
        // token分割
        final String token = StringUtils.substringAfter(authorization,
                TOKEN_SPLIT);
        // 根据token获取用户id
        return Long.parseLong(String.valueOf(StpUtil.getLoginIdByToken(token)));
    }
}
